#include "CXDTFileFinder.h"
#include <boost/filesystem.hpp>
#include <algorithm>
#include <string>

void CXDTFileFinder::addFindPath(const std::string& path)
{
	if (!path.empty())
	{
		m_searchPaths.push_back(path);
	}
}

bool CXDTFileFinder::findXDTFiles()
{
	// Clear previous results
	m_foundFiles.clear();
	
	for (const auto& path : m_searchPaths)
	{
		if (findXDTFilesInPath(path))
		{
			//todo: Log the found path
			
		}
	}
	return !m_foundFiles.empty();
}

std::vector<CXDTFile> CXDTFileFinder::getFindPaths() const
{
	return m_foundFiles;
}

bool CXDTFileFinder::findXDTFilesInPath(const std::string& path)
{
	try {
		// Check if directory exists
		if (!boost::filesystem::exists(path) || !boost::filesystem::is_directory(path)) {
			return false;
		}
		
		// Search for .xdt files in the directory
		for (const auto& entry : boost::filesystem::directory_iterator(path)) {
			if (boost::filesystem::is_regular_file(entry)) {
				std::string fileName = entry.path().filename().string();
				
				// Check if file has .xdt extension (case-insensitive)
				std::string lowerFileName = fileName;
				std::transform(lowerFileName.begin(), lowerFileName.end(), lowerFileName.begin(), ::tolower);
				
				if (lowerFileName.length() >= 4 && 
					lowerFileName.substr(lowerFileName.length() - 4) == ".xdt") {
					
					// Create CXDTFile object and add to results
					CXDTFile xdtFile(entry.path().string(), path);
					m_foundFiles.push_back(xdtFile);
				}
			}
		}
		
		return true;
	} catch (const std::exception& e) {
		// Handle any exceptions during file system operations
		return false;
	}
}